<template>
  <el-dialog
    :model-value="visible"
    width="500"
    top="35vh"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-form-item label="验证码" prop="code" class="items-center">
        <div class="flex items-center">
          <el-input
            v-model="formData.code"
            placeholder="请输入验证码"
            class="flex-1 h-40px"
          ></el-input>
          <img :src="imgUrl" class="ml-20px h-40px" alt="" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import systemApi from "@/api/system";

export interface FormData {
  code: string;
  uuid: string;
}

const visible = defineModel("visible", { type: Boolean, default: false });

const props = withDefaults(
  defineProps<{
    title: string;
    close?: () => void;
    confirm?: (data: FormData) => void;
  }>(),
  {}
);

const formData = ref<FormData>({
  code: "",
  uuid: "",
});
const rules = ref<FormRules<FormData>>({
  code: [{ required: true, message: "请输入验证码" }],
});
const formRef = ref<FormInstance>();

const handleClose = (): void => {
  setTimeout(() => {
    props?.close();
  }, 300);
};
const handleSubmit = (): void => {
  formRef.value.validate((valid) => {
    if (valid) {
      props.confirm?.(formData.value);
      handleClose();
    }
  });
};

const imgUrl = ref("");

const getCode = async () => {
  const data: any = await systemApi.getCodeByFindPwd();
  const { img, uuid } = data;
  imgUrl.value = `data:image/gif;base64,${img}`;
  formData.value.uuid = uuid;
};

onMounted(() => {
  getCode();
});
</script>
